package net.madarco.phpsense;

import java.util.Arrays;

import org.eclipse.dltk.ast.Modifiers;
import org.eclipse.dltk.core.IType;
import org.eclipse.dltk.internal.core.ModelElement;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.php.core.codeassist.ICompletionContext;
import org.eclipse.php.core.codeassist.ICompletionStrategy;
import org.eclipse.php.internal.core.PHPCorePlugin;
import org.eclipse.php.internal.core.codeassist.ICompletionReporter;
import org.eclipse.php.internal.core.codeassist.contexts.AbstractCompletionContext;
import org.eclipse.php.internal.core.codeassist.strategies.ClassMembersStrategy;
import org.eclipse.php.internal.core.typeinference.FakeField;
import org.eclipse.php.internal.core.typeinference.FakeMethod;

public class CompletionStrategy extends ClassMembersStrategy implements ICompletionStrategy {


	public CompletionStrategy(ICompletionContext context) {
		super(context);
	}

	public void apply(ICompletionReporter reporter) throws Exception {
		CompletionContext context = (CompletionContext) getContext();
		IType type = context.getLhsTypes()[0];
		String[] elementNames = context.getCompletionProposals();
		
		for (String element : elementNames) {
			if(element.startsWith("$")) {
				FakeField fakeField = new FakeField((ModelElement) type, element, Modifiers.AccPublic);
				reporter.reportField(fakeField, "", getReplacementRange(context), true);
			}
			else {
				int parenthesis = element.indexOf('(');
				FakeMethod fakeMethod;
				if(parenthesis == -1) {
					fakeMethod = new FakeMethod((ModelElement) type, element);
				}
				else {
					String name = element.substring(0, parenthesis);
					fakeMethod = new FakeMethod((ModelElement) type, name);
					String[] parameters = element.substring(parenthesis+1, element.length()-1).split(",\\s?");
					fakeMethod.setParameters(parameters);
					String[] initializers = new String[parameters.length];
					Arrays.fill(initializers, "");
					fakeMethod.setParameterInitializers(initializers);
				}
				reporter.reportMethod(fakeMethod, getSuffix(context), getReplacementRange(context));
			}

		}
	}

	public String getSuffix(AbstractCompletionContext abstractContext) {
		String nextWord = null;
		try {
			nextWord = abstractContext.getNextWord();
		} catch (BadLocationException e) {
			PHPCorePlugin.log(e);
		}
		return "(".equals(nextWord) ? "" : "()";
	}
}